package cn.thoughtworks.school.services;

import cn.thoughtworks.school.entities.NodeBBUser;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.repositories.NodeBBUserRepository;
import cn.thoughtworks.school.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class NodeBBUserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private NodeBBUserRepository nodeBBUserRepository;

    @Value("${nodeBB.url}")
    private String nodeBBUrl;

    @Value("${nodeBB.write-api-token}")
    private String nodeBBWriteApiToken;

    public Map fetchNodeBBFullName(String username, String password) {
        MultiValueMap<String, String> params= new LinkedMultiValueMap();
        params.add("username", username);
        params.add("password", password);

        RestTemplate template = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(params, headers);

        String getUserDetailUrl = nodeBBUrl + "/api/ns/login";
        ResponseEntity<Map> result = template.postForEntity(getUserDetailUrl, request, Map.class);

        return  result.getBody();
    }

    public NodeBBUser createNodeBBUserByUserId(Long userId) throws Exception {
        User user = userRepository.findById(userId).orElseThrow(() -> new BusinessException("当前用户不存在"));

        NodeBBUser nodeBBUser = new NodeBBUser();
        nodeBBUser.setUsername(user.getUsername());
        nodeBBUser.setPassword("Ts2lgMf8u%W@t6L6");
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", nodeBBWriteApiToken);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<NodeBBUser> entity = new HttpEntity<>(nodeBBUser, headers);
        String createUserUrl = nodeBBUrl + "/api/v2/users";
        ResponseEntity<HashMap> result = template.postForEntity(createUserUrl, entity, HashMap.class);


        if(HttpStatus.valueOf(result.getStatusCodeValue()) != HttpStatus.OK) {
            throw new IllegalAccessException("创建nodeBB用户失败");
        }

        Map payload = (Map) result.getBody().get("payload");
        Integer uid = (Integer) payload.get("uid");

        RestTemplate template2 = new RestTemplate();
        String getUserUrl = nodeBBUrl + "/api/v1/users";
        ResponseEntity<HashMap> result1 = template2.exchange(getUserUrl+"/"+uid, HttpMethod.GET, entity, HashMap.class);
        nodeBBUser.setUsername((String) result1.getBody().get("username"));
        nodeBBUser.setUserId(userId);
        nodeBBUserRepository.save(nodeBBUser);

        return nodeBBUser;
    }
}
